﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Nasty;

namespace CharacterFactory
{

    public partial class Main : Form
    {
        private string projectName;
        private int currentGroup = 0;
        private int currentSprite = 0;
        private List<SpriteGroup> listGroup = new List<SpriteGroup>();
        private List<Sprite> listSprite = new List<Sprite>();
        private List<Tile> listImage = new List<Tile>();
        private Character newCharacter = new Character();
        private bool saved = false;
        private bool firstAction = true;
        private bool pickedUpValue = true;

        public Main()
        {
            InitializeComponent();
            tabControl1.Enabled = false;
        }

        #region accessors
        public Character NewCharacter
        {
            get
            {
                return newCharacter;
            }
            set
            {
                newCharacter = value;
            }
        }
        public string ProjectName
        {
            get
            {
                return projectName;
            }
            set
            {
                projectName = value;
            }
        }
        #endregion

        //Create a new Character
        private void nouveauToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //If this is the first thing the user do when the software launchs
            if (firstAction == true)
            {
                firstAction = false;
                newProject();
            }
            else
            {
                //The user can open it
                DialogResult dlgRes = MessageBox.Show("Are you sure you want to create a new character without save your work?",
                            "New project", MessageBoxButtons.YesNoCancel);
                if (dlgRes == DialogResult.Yes)
                {
                    newProject();
                }
            }

            
            
        }

        private void reInitFields()
        {
            saveToolStripMenuItem.Enabled = false;
            tabControl1.Enabled = true;
            picturePortrait.Visible = false;
            pictureTile.Visible = false;
            textBoxBirthD.Text = "";
            textBoxBirthM.Text = "";
            textBoxBirthY.Text = "";
            textBoxFightingStyle.Text = "";
            textBoxFirstName.Text = "";
            textBoxLastName.Text = "";
            textBoxOriginX.Text = "";
            textBoxOriginY.Text = "";
            textBoxPosX.Text = "";
            textBoxPosY.Text = "";
            textBoxSizeHeight.Text = "";
            textBoxSizeWidth.Text = "";
            textBoxStory.Text = "";
            labelGroup.Text = "0";
            labelSprite.Text = "0";
        }

        private void newProject()
        {
            //Window dialog to write the name of the character
            NewProject n = new NewProject();
            Character c = new Character();
            newCharacter = c;
            n.ShowDialog();
            projectName = n.projectName;
            this.Text = "Character Factory ~~ " + projectName;
            //Dispose the second window
            n.Dispose();

            reInitFields();
            SpriteGroup s = new SpriteGroup();
            listGroup.Add(s);
            saveToolStripMenuItem.Enabled = true;

            string target = Directory.GetCurrentDirectory() + "\\" + projectName;
            if (Directory.Exists(target) == false)
            {
                Directory.CreateDirectory(target);
            }
            else //If the project already exists
            {
                //The user can open it
                DialogResult dlgRes = MessageBox.Show("This project already exists, do you want to open it?",
                            "Open existing project", MessageBoxButtons.YesNoCancel);
                if (dlgRes == DialogResult.Yes)
                {
                    openProject();
                }
            }
        }

        private void openProject()
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
            openFileDialog1.Filter = "STR files (*.str)|*.str";
            openFileDialog1.Multiselect = false;
            //openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileAcess fileAcess = new FileAcess();
                newCharacter = fileAcess.readCHRFile(openFileDialog1.FileName);
                this.Text = "Character Factory ~~ " + Path.GetFileNameWithoutExtension(openFileDialog1.FileName);

            }
        }

        public void characterToInterface(Character character)
        {
            saveToolStripMenuItem.Enabled = true;
            tabControl1.Enabled = true;
            
            reInitFields();

            if (character.spriteGroups.Count == 1)
            {
                if(character.spriteGroups[0].sprites.Count == 1)
                {
                    picturePortrait.Visible = true;
                    //picturePortrait.Image = character.spriteGroups[0].sprites[0].
                }
                
            }

            textBoxBirthD.Text = character.charInfo.dateOfBirth.Split('/')[0].ToString();
            textBoxBirthM.Text = character.charInfo.dateOfBirth.Split('/')[1].ToString();
            textBoxBirthY.Text = character.charInfo.dateOfBirth.Split('/')[2].ToString();
            textBoxFightingStyle.Text = "";
            textBoxFirstName.Text = character.charInfo.firstName;
            textBoxLastName.Text = character.charInfo.lastName;
            textBoxOriginX.Text = "";
            textBoxOriginY.Text = "";
            textBoxPosX.Text = "";
            textBoxPosY.Text = "";
            textBoxSizeHeight.Text = "";
            textBoxSizeWidth.Text = "";
            textBoxStory.Text = "";
            labelGroup.Text = "0";
            labelSprite.Text = "0";

        }

        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saved == true)
            {
                //Quit the software
                DialogResult dlgRes = MessageBox.Show("Are you sure you want to close without saving the character",
                                "Confirm Document Close", MessageBoxButtons.YesNoCancel);

                if (dlgRes == DialogResult.Yes)
                {
                    Application.Exit();
                }
            }
        }

        #region GroupButtons

        private void buttonAddGroup_Click(object sender, EventArgs e)
        {
            SpriteGroup g = new SpriteGroup();
            g.IdGroup = listGroup.Count;
            listGroup.Add(g);
            currentGroup = g.IdGroup;
            labelGroup.Text = currentGroup.ToString();
            labelSprite.Text = currentSprite.ToString();
            groupScrollBar.Maximum = currentGroup;
            buttonAddSprite.Enabled = true;
            buttonDeleteGroup.Enabled = true;

        }

        #endregion


        #region SpriteButtons

        private void buttonAddSprite_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
            openFileDialog1.Filter = "Bitmap files (*.bmp)|*.bmp|PNG files (*.png)|*.png|All files (*.*)|*.*";
            openFileDialog1.Multiselect = true;
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                #region if there is no group yet

                //if it is the first Sprite we import
                if (listGroup.Count == 0)
                {
                    //We cannot put the sprite in the Group 0 because it is used only for character's portrait
                    currentGroup = 1;

                    //Temporary group to add the group in the list
                    SpriteGroup g = new SpriteGroup();

                    //We have to increase the ID of the group
                    g.IdGroup = listGroup.Count - 1;

                    //Then we can add it to the group list
                    listGroup.Add(g);

                    //IF the user selected multiples files
                    foreach (string file in openFileDialog1.FileNames)
                    {
                        //Temporary Sprite to add the sprite in the group list
                        Sprite s = new Sprite();

                        //We have to count how many sprite there is already in the current group
                        currentSprite = listGroup[currentGroup].sprites.Count + 1;


                        s.IdSprite = currentSprite;
                        listGroup[currentGroup].sprites.Add(s);
                        Tile t = new Tile();
                        t.IdGroup = currentGroup;
                        t.IdSprite = currentSprite;
                        t.Sprite = (Bitmap)Bitmap.FromFile(file);
                        listImage.Add(t);
                    }
                    pictureTile.Image = listImage[listImage.Count].Sprite;
                }
                #endregion

                #region if there is already a group

                else
                {

                    //IF the user selected multiples files
                    foreach (string file in openFileDialog1.FileNames)
                    {
                        //Temporary Sprite to add the sprite in the group list
                        Sprite s = new Sprite();

                        //We have to count how many sprite there is already in the current group
                        currentSprite = listGroup[currentGroup].sprites.Count;


                        s.IdSprite = currentSprite;
                        listGroup[currentGroup].sprites.Add(s);
                        Tile t = new Tile();
                        t.IdGroup = currentGroup;
                        t.IdSprite = currentSprite;
                        t.Sprite = (Bitmap)Bitmap.FromFile(file);
                        listImage.Add(t);
                    }
                    pictureTile.Visible = true;
                    pictureTile.Image = listImage[listImage.Count - 1].Sprite;
                }
                #endregion

                spriteScrollBar.Minimum = 0;
                buttonDeleteSprite.Enabled = true;
            }
            openFileDialog1.Dispose();
            spriteScrollBar.Maximum = currentSprite;
            spriteScrollBar.Value = currentSprite;
            labelSprite.Text = currentSprite.ToString();
        }

        #endregion        


        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
            interfaceToCharacter();
            saved = true;

        }

        public void interfaceToCharacter()
        {
            newCharacter.charInfo.dateOfBirth = textBoxBirthD.Text + "/" + textBoxBirthM.Text + "/" + textBoxBirthY.Text;
            newCharacter.charInfo.firstName = textBoxFirstName.Text;
            newCharacter.charInfo.lastName = textBoxLastName.Text;
            newCharacter.charInfo.fightingStyle = textBoxFightingStyle.Text;
            newCharacter.charInfo.story = textBoxStory.Text;

        }

        private void groupScrollBar_Scroll(object sender, ScrollEventArgs e)
        {
            bool found = false;
            currentGroup = groupScrollBar.Value;
            labelGroup.Text = currentGroup.ToString();

            //CurrentSprite = 1 in order to see the animation from the start
            if (listGroup[currentGroup].sprites.Count == 0)
            {
                currentSprite = 0;
            }
            else
            {
                currentSprite = listGroup[currentGroup].sprites.Count - 1;
            }

            labelSprite.Text = currentSprite.ToString();
            foreach (Tile t in listImage)
            {
                if (t.IdGroup == currentGroup)
                {
                    if (t.IdSprite == currentSprite)
                    {
                        found = true;
                        pictureTile.Visible = true;
                        pictureTile.Image = t.Sprite;
                    }
                }
            }
            if (found == false)
            {
                pictureTile.Visible = false;
            }
            if (groupScrollBar.Value == 0)
            {
                buttonAddSprite.Enabled = false;
                buttonDeleteSprite.Enabled = false;
                buttonDeleteGroup.Enabled = false;
            }
            else
            {
                buttonAddSprite.Enabled = true;
                if (listGroup[currentGroup].sprites.Count != 0)
                {
                    buttonDeleteSprite.Enabled = true;
                }
                buttonDeleteGroup.Enabled = true;
            }
        }

        private void spriteScrollBar_Scroll(object sender, ScrollEventArgs e)
        {
            bool found = false;
            currentSprite = spriteScrollBar.Value;
            labelSprite.Text = currentSprite.ToString();
            foreach (Tile t in listImage)
            {
                if (t.IdGroup == currentGroup)
                {
                    if (t.IdSprite == currentSprite)
                    {
                        found = true;
                        pictureTile.Visible = true;
                        pictureTile.Image = t.Sprite;
                    }
                }
            }
            if (found == false)
            {
                pictureTile.Visible = false;
            }
        }

        private void buttonDeleteSprite_Click(object sender, EventArgs e)
        {
            //Quit the software
            DialogResult dlgRes = MessageBox.Show("Are you sure you want to delete the sprite : " + currentSprite,
                            "Confirm Sprite Deletion", MessageBoxButtons.YesNoCancel);

            if (dlgRes == DialogResult.Yes)
            {
                try
                {
                    newCharacter.spriteGroups[currentGroup].sprites.RemoveAt(currentSprite);
                    int image=0;
                    foreach (Tile t in listImage)
                    {
                        if (t.IdGroup == currentGroup && t.IdSprite == currentSprite)
                        {
                            listImage.Remove(t);
                            pictureTile.Image = listImage[image].Sprite;
                        }
                        image++;
                    }
                    
                    
                }
                catch (Exception xcp)
                {
                    MessageBox.Show(xcp.ToString());
                }
            }
            
        }

        private void buttonDeleteGroup_Click(object sender, EventArgs e)
        {
            //Quit the software
            DialogResult dlgRes = MessageBox.Show("Are you sure you want to delete the group : " + currentGroup,
                            "Confirm Group Deletion", MessageBoxButtons.YesNoCancel);

            if (dlgRes == DialogResult.Yes)
            {
                //We have to remove it from the spriteGroup
                //newCharacter.spriteGroups.RemoveAt(currentGroup);
                try
                {
                    newCharacter.spriteGroups[groupScrollBar.Value].sprites.Remove(newCharacter.spriteGroups[groupScrollBar.Value].sprites.Find(new Predicate<Sprite>(delegate(Sprite t) { return t.IdSprite.Equals(spriteScrollBar.Value); })));
                    listImage.Remove(listImage.Find(new Predicate<Tile>(delegate(Tile t) { return t.IdGroup.Equals(groupScrollBar.Value) && t.IdSprite.Equals(spriteScrollBar.Value); })));
                    pictureTile.Image = listImage.Find(new Predicate<Tile>(delegate(Tile t) { return t.IdGroup.Equals(groupScrollBar.Value) && t.IdSprite.Equals(spriteScrollBar.Value); })).Sprite;
                }
                catch (Exception xcp)
                {
                    MessageBox.Show(xcp.ToString());
                }
            }
        }

        private void OpenPortrait_Click(object sender, EventArgs e)
        {

        }

        private void buttonModifyActionName_Click(object sender, EventArgs e)
        {
            //Window dialog to write the name of the character
            NewAction n = new NewAction();
            n.ShowDialog();
            comboListAction.Items.Add(n.newActionName);

            //Dispose the second window
            n.Dispose();
        }

        private void buttonPickUpColor_Click(object sender, EventArgs e)
        {
            pickedUpValue = false;
            Cursor.Current = Cursors.Hand;
        }

        private void pictureTile_MouseClick(object sender, MouseEventArgs e)
        {
            Cursor.Current = Cursors.Default;
            if (pickedUpValue == false)
            {
                if ((pictureTile.PointToClient(Cursor.Position).X < pictureTile.Image.Width) && (pictureTile.PointToClient(Cursor.Position).Y < pictureTile.Image.Height))
                {
                    try
                    {
                        Color c = (pictureColor.Image as Bitmap).GetPixel(pictureColor.PointToClient(Cursor.Position).X, pictureColor.PointToClient(Cursor.Position).Y);
                        label1.Text = c.ToString();
                        Bitmap b = new Bitmap(pictureColor.Width, pictureColor.Height);
                        for (int i = 0; i < pictureColor.Width; i++)
                        {
                            for (int k = 0; k < pictureColor.Height; k++)
                            {
                                b.SetPixel(i, k, c);
                            }
                        }
                        pictureColor.Image = b;
                    }
                    catch (Exception xcp)
                    {
                        MessageBox.Show(xcp.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Invalid selection");
                }
                pickedUpValue = true;
            }
        }

        private void writeSTRFile()
        {

        }

        private void ouvrirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openProject();
        }

        

    }
}
